<template>
  <div class="page-service-group">
    <Breadcrumb separator=">">
      <BreadcrumbItem :to="'/home/environment/' + $route.params.environmentId + '/info'">
        <Tooltip :content="'环境(' + envName + ')'" placement="top">{{envName}} </Tooltip>
      </BreadcrumbItem>
      <BreadcrumbItem>
        <Tooltip :content="'服务组(' + serviceGroup.name + ')'" placement="top"> {{serviceGroup.name}} </Tooltip>
      </BreadcrumbItem>
    </Breadcrumb>

    <h4 class="zl-title">基本信息</h4>
    <div class="environment-info">
      <Spin fix v-if="infoLoading"></Spin>
      <div class="environment-info-box" v-else>
        <Row :gutter="10">
          <Col span="8" class="f-nowrap"><span class="info-title">名称：</span>{{serviceGroup.name}}</Col>
          <Col span="8" class="f-nowrap"><span class="info-title">容器数：</span>{{serviceGroup.containerCount}}</Col>
          <Col span="8"><span class="info-title">服务数：</span>{{serviceGroup.serviceCount}}</Col>
          <Col span="24">描述：{{serviceGroup.description || '暂无描述'}}</Col>
        </Row>
      </div>
    </div>

    <!-- 服务列表 -->
    <h4 class="zl-title">服务列表
      <div class="fr">
        <search placeholder="搜索服务" @change="searchService"></search>
        <Button type="primary" @click="addModifyService()" class="button-add" v-if="hasPermission($store, $route.params.environmentId, 'SERVICE_POST_ENV|GROUP')">
          <Icon type="md-add" />
          <span class="button-name">添加服务</span>
        </Button>
      </div>
    </h4>
    <div class="zl-page-loading" v-if="tableLoading">
      <Spin class="zl-page-loading" fix></Spin>
    </div>
    <Table :columns="columns" :data="serviceList" class="service-table" v-else></Table>

    <!-- 新增弹窗 -->
    <service-add-modal :visible.sync="serviceAddVisible" :params="serviceParams" @finish="addModifyServiceFinish"></service-add-modal>

    <!-- 升级弹窗 -->
    <Modal v-model="updateVisible" title="镜像升级" :loading="true" @on-ok="imageUpdateConfirm" >
      <Form :label-width="80" class="image-update-modal" label-position="left">
        <FormItem label="镜像版本">
          <Select v-model="imageForm.imageVersion">
            <Option value="image.name" v-for="image in imageVersionList" :key="image.name">{{image.name}}</Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>

  </div>
</template>

<script>
  import Search from '@/components/search'
  import ServiceAddModal from '@/components/add-service/modal'
  import Fetch from '@/api/request'
  export default {
    name: 'service-group',
    components: {Search, ServiceAddModal},
    data() {
      return {
        serviceGroup: {},
        envName: '',
        serviceList: [],
        columns: [{
          title: '启用状态',
          align: 'center',
          width: 80,
          render: (h, params) => {
            let cls = 'zl-badge'
            if (params.row.status === 'stopped') {
              cls = 'zl-badge badge-warning'
            } else if (params.row.status !== 'active') {
              cls = 'zl-badge badge-error'
            }
            return h('div', {
              class: [cls]
            }, '')
          }
        }, {
          title: '服务名称',
          width: 160,
          render: (h, params) => {
            return h('span', {
              class: 'zl-link',
              on: {
                click: () => {
                  this.serviceDetail(params.row)
                }
              }
            }, params.row.id)
          }
        }, {
          title: '镜像地址',
          key: 'image'
        }, {
          title: '容器数',
          key: 'replicas',
          width: 70,
          render: (h, params) => {
            let btnList = [h('span', params.row.replicas)]
            if (this.hasPermission(this.$store, this.$route.params.environmentId, 'SERVICE_PATCH_ENV|GROUP')) {
              btnList = [
                h('Icon', {
                  props: {
                    type: 'md-remove'
                  },
                  class: 'icon-mani',
                  on: {
                    click: () => {
                      this.podCount(params.row, -1)
                    }
                  }
                }),
                h('span', params.row.replicas),
                h('Icon', {
                  props: {
                    type: 'md-add'
                  },
                  class: 'icon-mani',
                  on: {
                    click: () => {
                      this.podCount(params.row, 1)
                    }
                  }
                })
              ]
            }
            return h('div', {
              class: 'pod-render'
            }, btnList)
          }
        }, {
          title: '创建时间',
          key: 'creationTimestamp',
          width: 160
        }, {
          title: '操作',
          align: 'center',
          width: 150,
          render: (h, params) => {
            let mani = []
            let btnList = []
            if (this.hasPermission(this.$store, this.$route.params.environmentId, 'SERVICE_DELETE_ENV|GROUP')) {
              mani.push(h('div', {
                class: 'button-inner',
                on: {
                  click: () => {
                    this.serviceUpdate(params.row)
                  }
                }
              }, [
                h('Icon', {
                  props: {
                    type: 'md-arrow-round-up'
                  }
                }, ''),
                '升级'
              ]))
            }
            if (this.hasPermission(this.$store, this.$route.params.environmentId, 'SERVICE_DELETE_ENV|GROUP') &&
              params.row.id !== 'mysql' && (params.row.type !== 'statefulSet' &&
              (params.row.status === 'active' || params.row.status === 'inactive' || params.row.status === 'degrade'))) {
              btnList.push(h('DropdownItem', [
                h('div', {
                  class: 'button-inner',
                  on: {
                    click: () => {
                      this.addModifyService(params.row)
                    }
                  }
                }, [
                  h('Icon', {
                    props: {
                      type: 'ios-create-outline'
                    }
                  }, ''),
                  '编辑'
                ])
              ]))
              btnList.push(h('DropdownItem', [
                h('div', {
                  class: 'button-inner',
                  on: {
                    click: () => {
                      this.addModifyService(params.row, true)
                    }
                  }
                }, [
                  h('Icon', {
                    props: {
                      type: 'ios-copy'
                    }
                  }, ''),
                  '克隆'
                ])
              ]))
            }
            if ((this.hasPermission(this.$store, this.$route.params.environmentId, 'SERVICE_PATCH_ENV|GROUP') &&
            params.row.type !== 'statefulSet' &&
            (params.row.status === 'active' || params.row.status === 'inactive' || params.row.status === 'degrade')) ||
            (this.hasPermission(this.$store, this.$route.params.environmentId, 'SERVICE_PATCH_ENV|GROUP') &&
            params.row.type !== 'statefulSet' && params.row.status === 'stopped') ||
            (this.hasPermission(this.$store, this.$route.params.environmentId, 'SERVICE_PATCH_ENV|GROUP') &&
            params.row.type === 'statefulSet')) {
              btnList.push(h('DropdownItem', [
                h('div', {
                  class: 'button-inner',
                  on: {
                    click: () => {
                      this.removeService(params.row)
                    }
                  }
                }, [
                  h('Icon', {
                    props: {
                      type: 'md-trash'
                    }
                  }, ''),
                  '删除'
                ])
              ]))
            }
            if (this.hasPermission(this.$store, this.$route.params.environmentId, 'SERVICE|START_POST_ENV|GROUP|SERVICE') &&
            params.row.type !== 'statefulSet' && params.row.status === 'stopped') {
              btnList.push(h('DropdownItem', [
                h('div', {
                  class: 'button-inner',
                  on: {
                    click: () => {
                      this.startService(params.row)
                    }
                  }
                }, [
                  h('Icon', {
                    props: {
                      type: 'ios-play'
                    }
                  }, ''),
                  '启用'
                ])
              ]))
            }

            if (this.hasPermission(this.$store, this.$route.params.environmentId, 'SERVICE|STOP_POST_ENV|GROUP|SERVICE') &&
            params.row.type !== 'statefulSet' &&
            (params.row.status === 'active' || params.row.status === 'inactive' || params.row.status === 'degrade')) {
              btnList.push(h('DropdownItem', [
                h('div', {
                  class: 'button-inner',
                  on: {
                    click: () => {
                      this.stopService(params.row)
                    }
                  }
                }, [
                  h('Icon', {
                    props: {
                      type: 'md-pause'
                    }
                  }, ''),
                  '停止'
                ])
              ]))
            }

            if (this.hasPermission(this.$store, this.$route.params.environmentId, 'SERVICE|REBOOT_DELETE_ENV|GROUP|SERVICE') &&
            params.row.type !== 'statefulSet' &&
            (params.row.status === 'active' || params.row.status === 'inactive' || params.row.status === 'degrade')) {
              btnList.push(h('DropdownItem', [
                h('div', {
                  class: 'button-inner',
                  on: {
                    click: () => {
                      this.ServiceReboot(params.row)
                    }
                  }
                }, [
                  h('Icon', {
                    props: {
                      type: 'md-power'
                    }
                  }, ''),
                  '重启'
                ])
              ]))
            }

            mani.push(h('Dropdown', {
              class: 'service-mani',
              props: {
                placement: 'bottom-end',
                trigger: 'click'
              }
            }, [
              h('Icon', {
                class: 'service-more',
                props: {
                  type: 'ios-more'
                }
              }),
              h('DropdownMenu', {
                slot: 'list'
              }, btnList)
            ]))

            return h('div', {
              class: 'service-render'
            }, mani)
          }
        }],
        serviceAddVisible: false,
        infoLoading: true,
        tableLoading: true,
        serviceParams: {},
        imageForm: {
          imageVersion: '',
          groupId: '',
          serviceId: ''
        },
        imageVersionList: [],
        updateVisible: false
      }
    },
    mounted() {
      let vm = this
      vm.$nextTick(function () {
        vm.envName = JSON.parse(localStorage.getItem('envionmentSelect')).environmentName
      })
      vm.init()
    },
    methods: {
       // 获取访问权
      getAccessRight() {
        Fetch.get({
          url: '/api/environments/' + this.$route.params.environmentId + '/ingresses'
        }).then((res) => {
          // 将二级数组所有访问权拼装、合并成一个数组
          let accessTemp = []
          for (let i = 0; i < res.data.length; i++) {
            const access = res.data[i]
            for (let j = 0; j < access.paths.length; j++) {
              const path = access.paths[j]
              accessTemp.push(Object.assign({serviceId: path.serviceId, link: 'http://' + access.host + path.path}, access))
            }
          }
          // 将访问权映射到服务上
          for (let k = 0; k < this.serviceList.length; k++) {
            const service = this.serviceList[k]
            for (let j = 0; j < accessTemp.length; j++) {
              const access = accessTemp[j]
              if (access.serviceId === service.id || access.serviceId === service.id + '-management') {
                this.$set(service, 'access', access)
              }
            }
          }
        })
      },
      // pod数增删
      podCount(service, offset) {
        if (service.replicas + offset < 0) {
          this.$Message.info({
            content: '当前服务已不存在副本数!',
            duration: this.DURATION
          })
          return
        }
        if (this.podModifing) {
          return
        }
        this.podModifing = true
        if (service.replicas + offset === 0) {
          this.$Modal.confirm({
            title: '系统提示',
            content: '副本数为0，意味着停止该服务！',
            onOk: () => {
              this.podHandle(service, offset)
            }
          })
        } else {
          this.podHandle(service, offset)
        }
      },
      podHandle(service, offset) {
        Fetch.patch({
          url: '/api/pod/add',
          params: {
            environmentId: this.$route.params.environmentId,
            groupId: this.$route.params.groupId,
            serviceId: service.id,
            data: {
              patchType: 'replicas',
              replicas: service.replicas + offset
            }
          },
          done: () => {
            this.podModifing = false
            service.replicas = service.replicas + offset
          }
        }).then((res) => {
          this.$Message.success({
            content: offset > 0 ? '新增容器成功！' : '减少容器成功！',
            duration: this.DURATION
          })
        })
      },
      // 确定升级镜像
      imageUpdateConfirm() {
        Fetch.patch({
          url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + this.imageForm.groupId + '/services/' + this.imageForm.serviceId,
          params: {
            environmentId: this.$route.params.environmentId,
            groupId: this.imageForm.groupId,
            serviceId: this.imageForm.serviceId,
            image: this.imageForm.image + ':' + this.imageForm.imageVersion,
            patchType: 'image'
          }.then((res) => {
            this.$Message.success({
              content: '镜像升级成功！',
              duration: this.DURATION
            })
            this.init()
          })
        })
      },
      // 升级镜像弹出弹窗
      serviceUpdate(service) {
        this.imageForm.serviceId = service.id
        this.imageForm.groupId = this.serviceGroup.id
        this.imageForm.image = service.image.split(':')[0]
        Fetch.get({
          url: '/api/harbor/images/' + service.image.split(':')[0] + '/tags?environment=' + this.$route.params.environmentId
        }).then((res) => {
          this.imageVersionList = res.data
          this.updateVisible = true
        })
      },
      // 启用服务
      startService(service) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定启用' + service.id + '服务',
          loading: true,
          onOk: () => {
            Fetch.post({
              url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + this.serviceGroup.id + '/services/' + service.id + '/start',
              done: () => {
                this.$Modal.remove()
              }
            }).then((res) => {
              this.$Message.success({
                content: '启用' + service.id + '服务成功！',
                duration: this.DURATION
              })
              this.init()
            })
          }
        })
      },
      // 停止服务
      stopService(service) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定停止' + service.id + '服务',
          loading: true,
          onOk: () => {
            Fetch.post({
              url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + this.serviceGroup.id + '/services/' + service.id + '/stop',
              done: () => {
                this.$Modal.remove()
              }
            }).then((res) => {
              this.$Message.success({
                content: '停止' + service.id + '服务成功！',
                duration: this.DURATION
              })
              this.init()
            })
          }
        })
      },
      // 删除服务
      removeService(service) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定删除' + service.id + '服务',
          loading: true,
          onOk: () => {
            Fetch.delete({
              url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + this.serviceGroup.id + '/services/' + service.id,
              done: () => {
                this.$Modal.remove()
              }
            }).then((res) => {
              this.$Message.success({
                content: '删除' + service.id + '服务成功！',
                duration: this.DURATION
              })
              this.init()
            })
          }
        })
      },
      // 重启服务
      ServiceReboot(service) {
        this.$Modal.confirm({
          title: '系统提示',
          content: '确定重启' + service.id + '服务',
          loading: true,
          onOk: () => {
            Fetch.delete({
              url: '/api/environments/' + this.$route.params.environmentId + '/groups/' + this.serviceGroup.id + '/services/' + service.id + '/reboot',
              done: () => {
                this.$Modal.remove()
              }
            }).then((res) => {
              this.$Message.success({
                content: '重启' + service.id + '服务成功！',
                duration: this.DURATION
              })
              this.init()
            })
          }
        })
      },
      // 添加服务完成
      addModifyServiceFinish() {
        this.init()
      },
      // 添加修改服务， 有service则为修改
      addModifyService(service, isClone) {
        if (!service) {
          this.serviceParams = {
            groupId: this.serviceGroup.id,
            clone: false
          }
        } else {
          let t = {
            groupId: this.serviceGroup.id,
            clone: !!isClone,
            service: Object.assign({}, service)
          }
          if (isClone) {
            t.service = Object.assign({}, service, {id: service.id + '-copy'})
          }
          this.serviceParams = t
        }
        this.serviceAddVisible = true
      },
      // 服务详情
      serviceDetail(service) {
        this.$router.push('/home/environment/' + this.$route.params.environmentId + '/info/' + this.serviceGroup.id + '/' + service.id)
      },
      // 初始数据
      init() {
        this.info()
        this.services()
      },
      // 获取服务组信息
      info(params) {
        Fetch.get({
          url: '/api/serviceGroup/info',
          params: {
            groupId: this.$route.params.groupId,
            environmentId: this.$route.params.environmentId
          },
          done: () => {
            this.infoLoading = false
          }
        }).then((res) => {
          this.serviceGroup = res.data
        })
      },
      services() {
        Fetch.get({
          url: '/api/serviceGroup/services',
          params: {
            groupId: this.$route.params.groupId,
            environmentId: this.$route.params.environmentId
          },
          done: () => {
            this.tableLoading = false
          }
        }).then((res) => {
          this.serviceList = res.data
          this.getAccessRight()
        })
      },
      // 根据名称搜索服务组
      searchService(search) {
        let temp = []
        this.serviceGroup.serviceList.forEach((service) => {
          if (service.id.indexOf(search) !== -1) {
            temp.push(service)
          }
        })
        this.serviceList = temp
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .environment-info {
    position: relative;
    min-height: 100px;
  }
  .environment-info-box {
    line-height: 32px;
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    border: 1px solid #eee;
  }
  .button-add {
    .iconfont:hover {
      color: #fff;
    }
  }
  .service-table {
    margin-top: 20px;
    margin-bottom: 50px;
  }
  .btn-mani {
    margin-left: 10px;
  }
  .service-more {
    font-size: 22px;
  }
</style>
